package com.blog.controller;


import com.blog.common.prop.JwtProp;
import com.blog.common.result.R;
import com.blog.common.result.ResponseEnum;
import com.blog.common.thread.BaseThread;
import com.blog.common.utils.JwtUtil;
import com.blog.entity.dto.UserLoginDTO;
import com.blog.entity.dto.UserPwdDTO;
import com.blog.entity.po.User;
import com.blog.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author author
 * @since 2024-03-24
 */

/**
 * 用户控制器
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private IUserService userService;

    @Autowired
    private JwtProp jwtProp;

    /**
     * 登录
     *
     * @param dto
     * @return
     */
    @PostMapping("/login")
    public R login(@RequestBody UserLoginDTO dto) {
        log.info("要登录的用户参数：{}", dto);
        User user = userService.login(dto);
        HashMap<String, Object> map = new HashMap<>();
        map.put("userId", user.getId());
        String jwt = JwtUtil.createJWT(jwtProp.getSecretKey(), jwtProp.getTtlMillis(), map);
        return R.success(jwt);
    }

    /**
     * 注册
     *
     * @param dto
     * @return
     */
    @PostMapping("/register")
    public R register(@RequestBody UserLoginDTO dto) {
        log.info("要注册的用户参数：{}", dto);
        userService.register(dto);
        return R.success();
    }


    /**
     * 获取用户信息
     *
     * @return
     */
    @GetMapping("/info")
    public R<User> info() {
        String id = BaseThread.getId();
        log.info("当前用户id：{}", id);
        User user = userService.getById(id);
        user.setPassword("");
        return R.success(user);
    }


    @PutMapping("/updateInfo")
    public R updateInfo(@RequestBody User user) {
        log.info("要修改的用户信息：{}", user);
        userService.updateInfo(user);
        return R.success(ResponseEnum.SUCCESS);
    }


    @PutMapping("/updatePwd")
    public R updatePwd(@RequestBody UserPwdDTO dto) {
        log.info("要修改的用户密码：{}", dto);
        userService.updatePwd(dto);
        return R.success(ResponseEnum.SUCCESS);
    }

}
